/**
 * @author:  maybe
 * @date: 2024/1/17
 * @des: 地址管理
 */
const axios = require('axios');
const qs = require('qs');
const  Address  = require('../collection/address')
const { removeEmptyValues } = require('../../utils/methold')
const Goods = require("../collection/goods");
const  { bdMap} = require('../../utils/config')
module.exports = {
    add: async (ctx) => {
        let  _timer = null
        try {
            const lat = ctx.request.body.lat || bdMap.lat
            const lng = ctx.request.body.lng || bdMap.lng
            const radius = ctx.request.body.radius || 1500
            await Address.deleteMany({})
            const query = {
                query: '小区',
                location: `${lat},${lng}`,
                output: 'json',
                ak: bdMap.ak,
                radius: radius,
                page_size:10,
                page_num: 1,
                tag: '小区'
            }
             _timer = setInterval(async() => {
                const resAddress = await axios.get('https://api.map.baidu.com/place/v2/search?' + qs.stringify(query))
                if (resAddress.data.status !== 0) {
                    clearInterval(_timer)
                    return
                }
                if (query.page_num > 10) {
                    clearInterval(_timer)
                    return
                }
                if (resAddress.data.results.length < query.page_size) {
                    clearInterval(_timer)
                }
                await Address.insertMany(resAddress.data.results)
                query.page_num += 1
            },1000)
            ctx.body = {
                status: 200,
                msg: '添加成功',
                data: []
            }

        }
        catch (error) {
            if(_timer){
                clearInterval(_timer)
            }
            ctx.body = {
                status: 500,
                msg: '添加失败',
                data: []
            }
        }
    },
    getList: async (ctx) => {
        try {
            const {
                pageSize,
                currentPage
            } = ctx.request.query
            let query = {
                ...ctx.request.query
            }
            delete query.pageSize
            delete query.currentPage
            query.hasOwnProperty('total')? delete query.total : ''
            // 清除空的字段
            query = removeEmptyValues(query)
            // 模糊匹配名称
            if(query.hasOwnProperty('name')) {
                query.name = {$regex: query.name}
            }
            const list = await Address.find(query).sort().skip(pageSize * (currentPage - 1)).limit(pageSize)
            const total = await Address.countDocuments();
            ctx.body = {
                status: 200,
                msg: '获取成功',
                data: {
                    list,
                    total,
                    pageSize: Number(pageSize),
                    currentPage: Number(currentPage)
                }
            }
        } catch (error) {
            ctx.body = {
                status: 500,
                msg: '获取失败',
                data: []
            }
        }
    },
    edit: async (ctx) => {
        try {
            const  {
                addressId,
            } = ctx.request.body
            if (!addressId) {
                ctx.body = {
                    status: 'error',
                    msg: '必要id 不能为空!'
                }
            }
            let params = {
                ...ctx.request.body
            }
            delete params.addressId
            params = removeEmptyValues(params)
            const filter = { _id: `${addressId}` }
            params.updateDate = new Date() // 修改时间更新下
            const res = await Address.updateOne(filter,{ $set:params })
            if(res.acknowledged && res.modifiedCount) {
                ctx.body = {
                    status: 200,
                    data: {},
                    msg: '修改成功'
                }
            }else {
                ctx.body = {
                    status: 'error',
                    data: {},
                    msg: '数据异常'
                }
            }
        }
        catch (error) {
            ctx.body = {
                status: 500,
                msg: '修改失败',
                data: []
            }
        }
    },
    delete: async (ctx) => {
        try {
            const {
                addressId
            } = ctx.request.query
            if (!addressId) {
                ctx.body = {
                    status: 'error',
                    msg: '必要id 不能为空!'
                }
            }
            const filter = {_id: `${addressId}`}
            const res = await Address.deleteOne(filter)
            if (res.acknowledged && res.deletedCount) {
                ctx.body = {
                    status: 200,
                    data: {},
                    msg: '删除成功'
                }
            } else {
                ctx.body = {
                    status: 'error',
                    data: {},
                    msg: '数据异常'
                }
            }
        }
        catch (err) {
            ctx.body = {
                status: 500,
                msg: '删除失败',
                data: []
            }
        }
    }

}